package com.kstech.ks_gaz01.xmlAddress

import android.content.Context
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.util.LinkedList

/**
 * author: blankii
 * created on: 2024/6/3 16:56
 * description:
 * 1 解析xml ，统计modbus 地址是否重合
 * 2 找出空隙地址区域
 * 3 可视化
 */
object XmlAddressStatisticUtils {
    private val TAG: String = "XmlAddressStatisticUtils"
    fun start(context: Context, xmlFileName: String, space: Int, ignoreException: Boolean = false): String {
        return parseXml(context, xmlFileName, space,ignoreException)
    }

    /**
     * ignoreException:
     */
    fun parseXml(
        context: Context, xmlFileName: String, space: Int, ignoreException: Boolean
    ): String {
        val stringBuilder = StringBuilder()
        val list = LinkedList<Int>()
        if (!xmlFileName.contains(".xml")) throw Exception("${TAG}:xml文件名称传入不合法")
        var pullParser: XmlPullParser? = null
        // 创建Pull解析器
        pullParser = XmlPullParserFactory.newInstance().newPullParser()
        // 设置xml数据源
        val inputStream = context.resources.assets.open("cars/$xmlFileName")
        pullParser.setInput(inputStream, null)
        var eventType: Int = pullParser.eventType
        while (eventType != XmlPullParser.END_DOCUMENT) {
            when (eventType) {
                XmlPullParser.START_DOCUMENT -> {
                    // 开始解析，可以在这里做一些初始化

                }

                XmlPullParser.START_TAG -> {
                    val currentNodeName: String = pullParser.name
                    var address = ""
                    if (currentNodeName == "item") {
                        if (pullParser.attributeCount >= 4) {
                            address = pullParser.getAttributeValue(null, "para0")
                        }
                    } else if (currentNodeName == "child") {
                        if (pullParser.attributeCount > 1) {
                            address = pullParser.getAttributeValue(null, "itemsAddress")
                        }
                    } else if (currentNodeName == "group") {
                        if (pullParser.attributeCount > 1) {
                            address = pullParser.getAttributeValue(null, "itemsAddress")
                        }
                    }
                    if (address.isNotEmpty()) {
                        if (list.contains(address.toInt())) {
                            stringBuilder.append("异常：地址:$address 出现重复\n")
                        }
                        list.add(address.toInt())
                    }
                }

                XmlPullParser.END_TAG -> {

                }

                XmlPullParser.END_DOCUMENT -> {

                }

                else -> {}
            }
            // 继续解析下一个事件
            eventType = pullParser.next()
        }
        if (!ignoreException && stringBuilder.isNotEmpty()) {
            return stringBuilder.toString()
        }
        //除去心跳44360
        //除去故障码44460 44461 44462
        list.add(44360)
        list.add(44460)
        list.add(44461)
        list.add(44462)
        return printSortLinkedList(list, space)
    }

    /**
     * space:要多少个连续的空间
     *
     */
    private fun printSortLinkedList(list: LinkedList<Int>, space: Int): String {
        val stringBuilder = StringBuilder()
        val END = 45000
        var start = 43711 //43700 开始用在全局指令中了
        var sIndex = 0
        val resList = LinkedList<Int>()
//        val sortList =
//        println("Sorted ascending: ${list.sorted()}")
        for (i in start until END) {
            if (!list.contains(i)) {
                resList.add(i)
            }
        }
        for (y in 0 until resList.size - 2) {
            if (resList[y] + 1 != resList[y + 1]) {
                sIndex = y + 1
            } else {
                if (y + 1 - sIndex >= space) {
                    stringBuilder.append("未启用的起始位:${resList[sIndex]}\n")
                    sIndex = y + 1
                }
            }
        }
        return stringBuilder.toString()
    }
}